/**
 * 去掉输入框中两边空格
 * 使用 <el-input v-model="xxx" v-trim></el-input>
 */
function dispatchEvent (el: any, type: any) {
  const evt = document.createEvent('HTMLEvents')
  evt.initEvent(type, true, true)
  el.dispatchEvent(evt)
}
export default {
  name: 'trim',
  inserted (el: any) {
    const inputEle = el.tagName === 'INPUT' ? el : el.querySelector('input')
    const handler = function (event: any) {
      const newVal = event.target.value.trim()
      if (event.target.value !== newVal) {
        event.target.value = newVal
        dispatchEvent(inputEle, 'input')
      }
    }
    el.inputEle = inputEle
    el._blurHandler = handler
    inputEle.addEventListener('blur', handler)
  },
  unbind (el: any) {
    const { inputEle } = el
    inputEle.removeEventListener('blur', el._blurHandler)
  }
}
